package com.rt.tmpt.controller.springmvc.admin;

import com.rt.tmpt.dto.A1OperationlogDto;
import com.rt.tmpt.dto.A2UserDto;
import com.rt.tmpt.dto.Result;
import com.rt.tmpt.others.singleuser.OnlineUserBindingListener;
import com.rt.tmpt.service.ILoginFailureService;
import com.rt.tmpt.service.IOperationlogService;
import com.rt.tmpt.service.IOrgService;
import com.rt.tmpt.service.ISecurityV2Service;
import com.rt.tmpt.utils.MD5Util;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Random;

@Api(tags = "用户控制类")
@Controller
@RequestMapping("/admin123")
@Slf4j
public class EmpAction {
    public static final String VALIDATE_CODE = "validateCode";


    @Resource
    private ILoginFailureService loginFailureService;
    @Resource
    private IOperationlogService operationlogService;
    @Resource
    private ISecurityV2Service securityV2Service;
    @Resource
    private IOrgService orgService;

    /**
     * 用户登录
     *
     * @return
     */
    @ApiOperation(value = "登录")//swagger 当前接口注解
    @PostMapping(value = "/emp_login")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "username", value = "用户名", dataType = "String", required = true),
            @ApiImplicitParam(paramType = "query", name = "password", value = "密码", dataType = "String", required = true),
            @ApiImplicitParam(paramType = "query", name = "validateCode", value = "验证码", dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "showMode", value = "显示方式", dataType = "String")
    })
    public String login(Model model, String username,
                        String password,
                        String validateCode, String showMode,
                        HttpServletRequest request) {
        A1OperationlogDto oprDtoBack = new A1OperationlogDto(request, A1OperationlogDto.UserTypeBack);
        Result result = new Result();
        String r = "";
        try {
            oprDtoBack.setLogTypeName("登录[后台]");
            HttpSession session = request.getSession();

            //6次登录密码错误，锁定1小时
            int hourInt = 1;
            int limitFailureTimes = 6;

            //检测验证码
			/*Object isLoginSuccessBack = session.getAttribute("_isLoginSuccessBack");
			if(isLoginSuccessBack!=null){
				if(!isValidateCodeOK(validateCode, request)){
					r = "验证码错误";
					oprDtoBack.setDescription("登录名:"+username+":"+ r);
					operationlogService.addOperationlog(oprDtoBack);
					model.addAttribute("result",r);
					return "indexBefore1";
				}
			}*/

            String passwordNoEncode = password;
            String psdMd5 = password;
            try {
                //解密
                //String keyPairLocation = Config.keyPairLocation;
                //keyPairLocation = null;
                //DecodeAction decodeAction = new DecodeAction(keyPairLocation);
                //password = decodeAction.execute(password);
                passwordNoEncode = password;
                //password by md5 for store
                psdMd5 = password + username;
                //log.debug("psdMd5:"+psdMd5);
                psdMd5 = MD5Util.toMD5ForApp(psdMd5);
                //log.debug("psdMd5:"+psdMd5);
            } catch (Exception e) {
                e.printStackTrace();
                r = "密码加解密出错";
                model.addAttribute("result", r);
                oprDtoBack.setDescription("登录名:" + username + ":" + r);
                operationlogService.addOperationlog(oprDtoBack);
                return "indexBefore1";
            }

            //验证用户账号与密码是否对应
            A2UserDto empDto = securityV2Service.getUserByLoginname(username);
            if (empDto == null) {
                r = "用户名不存在";
                model.addAttribute("result", r);
                oprDtoBack.setDescription("登录名:" + username + ":" + r);
                operationlogService.addOperationlog(oprDtoBack);
                return "indexBefore1";
            }
            if (empDto.getDeleteFlag() == 1) {
                r = "用户状态不正常";
                model.addAttribute("result", r);
                oprDtoBack.setDescription("登录名:" + username + ":" + r);
                operationlogService.addOperationlog(oprDtoBack);
                return "indexBefore1";
            }


            //登录次数限制-开始 00
            Result resultLoginLimit = loginFailureService.loginBefore(0, empDto.getId(), 0, hourInt, limitFailureTimes);
            if (!resultLoginLimit.isSuccess()) {
                r = resultLoginLimit.getContentOnly();
                model.addAttribute("result", r);
                oprDtoBack.setDescription("登录名:" + username + ":" + r);
                operationlogService.addOperationlog(oprDtoBack);
                return "indexBefore1";
            }
            if (!empDto.getPassword().toLowerCase().equals(psdMd5.toLowerCase())) {
                session.setAttribute("_isLoginSuccessBack", -1);

                //登录次数限制-密码错误
                resultLoginLimit = loginFailureService.loginFailure(0, empDto.getId(), 0, hourInt, limitFailureTimes);
                if (!resultLoginLimit.isSuccess()) {
                    r = "密码不正确";
                    model.addAttribute("result", r);
                    oprDtoBack.setDescription("登录名:" + username + ":" + r);
                    operationlogService.addOperationlog(oprDtoBack);
                    return "indexBefore1";
                }

                r = "密码不正确；" + resultLoginLimit.getContentOnly();
                model.addAttribute("result", r);
                oprDtoBack.setDescription("登录名:" + username + ":" + r);
                operationlogService.addOperationlog(oprDtoBack);
                return "indexBefore1";
            }

            //login success , release data about the customer
            loginFailureService.loginRelease(0, empDto.getId(), 0);

            //UsernamePasswordAuthenticationToken实现 Authentication
            //UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, psdMd5.toLowerCase());
            // Place the last username attempted into HttpSession for views

            String email = empDto.getEmail();
            long userId = empDto.getId();
            session.setAttribute("username", username);
            session.setAttribute("userFullName", empDto.getName());
            session.setAttribute("userId", userId);
            session.setAttribute("password", passwordNoEncode);
            session.setAttribute("showMode", showMode);
            session.setAttribute("companyId", empDto.getCompanyId());
            final String toEmail = empDto.getEmail();


            //Send Email for validate
            final String randStr = this.genRandStr(6);
            session.setAttribute("_randStr", randStr);

            r = "用户名、密码校验正确";
            model.addAttribute("result", r);
            oprDtoBack.setDescription("登录名:" + username + ":" + r);
            operationlogService.addOperationlog(oprDtoBack);

            //init 岗位下级员工
            orgService.initPostUser(userId);

            //return "indexBefore2";
            //return result.success(r);
            return "indexBefore2";
        } catch (Exception e) {
            e.printStackTrace();
            r = e.getLocalizedMessage();
            model.addAttribute("result", r);
            //return "indexBefore1";
            //return result.fault(r);
            return "redirect:indexBefore1.jsp";
        }
    }

    /**
     * 生成count位随机数，发送email验证使用
     *
     * @param count
     * @return
     */
    private String genRandStr(int count) {
        Random random = new Random();
        String dataSourceStr = "0123456789";
        StringBuffer sRand = new StringBuffer();

        for (int i = 0; i < count; i++) {
            int index = random.nextInt(dataSourceStr.length());
            char dataChar = dataSourceStr.charAt(index);
            String rand = String.valueOf(dataChar);
            sRand.append(rand);
        }

        return sRand.toString();
    }

    /**
     * 重置密码
     *
     * @return
     */
    @ApiOperation(value = "重置密码")
    @PostMapping(value = "/template/user/templateEmpAjax_resetPassword")
    @ResponseBody
    public Result resetPassword(String username, String password, long empId) {
        Result result = new Result();
        try {
			/*System.out.println("----resetPassword------"+username);
			String psdMd5 = password+username;
			psdMd5 = MD5Util.toMD5ForApp(psdMd5);
			System.out.println("----resetPassword psdMd5------"+psdMd5);
			*/
            String psdBcrypt = new BCryptPasswordEncoder().encode(username);
            result = securityV2Service.resetPassword(empId, psdBcrypt);
        } catch (Exception e) {
            result.fault(e.getLocalizedMessage());
            e.printStackTrace();
        }
        return result;
    }


    private boolean isValidateCodeOK(String validateCode, HttpServletRequest request) {
        HttpSession session = request.getSession();

        Object obj = session.getAttribute(VALIDATE_CODE);
        String sessionValidateCode = (null == obj ? "" : obj.toString());
        //让上一次的验证码失效
        session.setAttribute(VALIDATE_CODE, null);
        String validateCodeParameter = validateCode;
        if (StringUtils.isEmpty(validateCodeParameter) || !sessionValidateCode.equalsIgnoreCase(validateCodeParameter)) {
            //throw new AuthenticationServiceException("验证码错误！");
            return false;
        }
        return true;
    }


    /**
     * 电子邮箱校验
     *
     * @return
     */
    @PostMapping(value = "/emp_emailValidate")
    @ApiOperation(value = "邮箱验证")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "username", value = "用户名", dataType = "String", required = true),
            @ApiImplicitParam(paramType = "query", name = "validateCode", value = "验证码", dataType = "String", required = true)
    })
    public String emailValidate(String validateCode, String username,
                                HttpServletRequest request, HttpServletResponse response) {
        System.out.println(username);
        System.out.println(validateCode);
        A1OperationlogDto oprDtoBack = new A1OperationlogDto(request, A1OperationlogDto.UserTypeBack);
        String r = "";
        oprDtoBack.setLogTypeName("登录[后台]");
        try {
            HttpSession session = request.getSession();
            String emailValidateCode = validateCode;
            String emailValidateCodeSession = (String) session.getAttribute("randStr");

			/*
			if(!emailValidateCode.equalsIgnoreCase(emailValidateCodeSession)){
				this.result = "电子邮箱校验码错误，请重新登录！";
				oprDtoBack.setDescription("登录名:"+username+":"+this.result);
				operationLogService.addOperationlog(oprDtoBack);
				return "indexBefore1";
			}
			*/

            //登录成功
            session.setAttribute("onlineUserBindingListener", new OnlineUserBindingListener(username));
            System.out.println("login success");
            return "index";
        } catch (Exception e) {
            e.printStackTrace();
            r = e.getLocalizedMessage();
            oprDtoBack.setDescription("登录名:" + username + ":" + r);
            operationlogService.addOperationlog(oprDtoBack);
            return "indexBefore1";
        }
    }

	/*
	public String singleUser(){
		Result result = new Result();
		try {
			HttpSession session = WebUtils.getRequest().getSession();
			ServletContext application = session.getServletContext();
			List<Userinfo> onlineUserList = (List<Userinfo>)application.getAttribute("onlineUserList");
			String username = (String)session.getAttribute("username");
			if(onlineUserList!=null){
				for(Userinfo userinfo: onlineUserList){
					if(userinfo.getUsername().equals(username)){
						userinfo.setLastAccessTime(DateTool.getCurrentDatetime());
					}
				}
			}
		} catch (Exception e) {
			result.fault("系统出错:"+e.getLocalizedMessage());
			this.result = JSONObject.fromObject(result.getMap()).toString();
		}
		return "jsonResult";
	}
    */


}
